package org.grow.erp.controller;

import org.grow.dto.PagedResult;
import org.grow.dto.erp.LeaveBillState;
import org.grow.erp.dao.LeaveBillMapper;
import org.grow.erp.entity.LeaveBill;
import org.grow.secure.exception.BillStateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.xml.sax.ext.Locator2;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Random;

/**
 * @Author: xwg
 * @CreateDate: 2022/5/30
 */

@RestController
@RequestMapping("/erp/leave")
public class LeaveController {

    @PostMapping("/test")
    public PagedResult<String> test(@RequestParam Integer days) {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("共享session获取当前登录人：" + name);
        if (days <= 0) {
            throw new BillStateException("用填写的户请假申请天数不正确 ：" + days);
        }
        System.out.println("使用mapper保存到数据库");
        return new PagedResult<String>(10L, Arrays.asList(name + "希望请假" + days + "天"));
    }

    private Random random = new Random();
    @Autowired
    private LeaveBillMapper leaveBillMapper;

    @PostMapping("/insert")
    public LeaveBill insert(@RequestBody LeaveBill leaveBill) {
        leaveBill.setLeaveCode(("LV" + System.currentTimeMillis()) + random.nextInt(10));
        leaveBill.setSubmitter(SecurityContextHolder.getContext().getAuthentication().getName());
        leaveBill.setLeaveBillState(LeaveBillState.toSubmit);
        leaveBill.setLogicDelete(false);
        leaveBill.setSubmitTime(null);
        leaveBill.setSupervisor(null);
        leaveBill.setManager(null);
        leaveBill.setUpdateTime(LocalDateTime.now());
        leaveBillMapper.insert(leaveBill);
        return leaveBill;
    }
}
